package com.sk.weichat.pay.sk;

import android.app.Activity;
import android.os.Handler;
import android.text.TextUtils;
import com.alipay.sdk.app.AuthTask;
import com.sk.weichat.R;
import com.sk.weichat.ui.me.redpacket.alipay.AuthResult;
import com.sk.weichat.ui.me.wallet.view.AuthCallbackView;
import com.sk.weichat.util.AppUtils;
import com.sk.weichat.util.AsyncUtils;
import com.sk.weichat.util.ToastUtil;
/**
*  支付宝授权
* */
public class AlipayAuth{

    private AuthCallbackView mAuthCallbackView;
    public AlipayAuth( AuthCallbackView mAuthCallbackView){
        this.mAuthCallbackView = mAuthCallbackView;
    }
    /**
     * 支付宝账户授权业务
     *
     */
    public void callAuth(Activity mActivity,String authInfo,boolean isBind) {
        AsyncUtils.doAsync(mActivity, t -> {
            AsyncUtils.runOnUiThread(mActivity, ctx -> {
                ToastUtil.showToast(ctx, R.string.tip_alipay_failed);
            });
        }, c -> {
            AuthTask authTask = new AuthTask(mActivity);
            // 调用授权接口，获取授权结果
            AuthResult aliResult = new AuthResult(authTask.authV2(authInfo, true), true);
            c.uiThread(r -> {
                if (TextUtils.equals(aliResult.getResultStatus(), "9000")) {
                    if (TextUtils.equals(aliResult.getResultCode(), "200")){
                        mAuthCallbackView.AlipayAuthCallbackResult(aliResult.getAuthCode());
                    }else if (TextUtils.equals(aliResult.getResultCode(), "1005")){
                        ToastUtil.showToast(mActivity, R.string.tips_auth_err1);
                    }else {
                        ToastUtil.showToast(mActivity, R.string.tips_auth_err2);
                    }
                }else if (TextUtils.equals(aliResult.getResultStatus(), "6001")){
                    new Handler().postDelayed(new Runnable(){
                        public void run() {
                            //execute the task
                            if (AppUtils.isAppForeground(mActivity)){//判断当前页是否在前台显示
                                if (isBind){//取消绑定提示
                                    ToastUtil.showToast(mActivity, R.string.tips_alipay_bind_err);
                                }else {//取消验证提示
                                    ToastUtil.showToast(mActivity, R.string.tips_verify_alipay_err);
                                }
                            }
                        }
                    }, 500);

                }
            });
        });
    }
}
